package cn.cs.common;

import cn.cs.pojo.CsUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtils {
    public static final String SUBJECT="cs_platform";
    public static final long EXPIRE = 1000*60*60*24*7;//过期时间为一周
    public static final String APPSECRET ="csplatfomr";//密钥

    /**
     * 生成 token
     * @param csUser
     * @return
     * */
    public static String geneJsonWebToken(CsUser csUser){
        if(csUser.getPhone() == null || csUser.getRealName() == null || csUser.getId() == null){
            return null;
        }
        final String token = Jwts.builder().setSubject(SUBJECT)
                .claim("name",csUser.getRealName())
                .claim("id",csUser.getId())
                .claim("phone",csUser.getPhone())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
                .signWith(SignatureAlgorithm.HS256,APPSECRET).compact();
        return token;
    }
    /**
     * 校验token
     * */
    public static Claims checkJWT(String token){
        try {
            final Claims claims = Jwts.parser().setSigningKey(APPSECRET).
                    parseClaimsJws(token).getBody();
            return claims;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
